package com.label.Config.DataSource;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisXMLLanguageDriver;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName DruidConfig
 * @Description //DruidConfig配置类
 * @Author singleZhang
 * @Email 405780096@qq.com
 * @Date 2020/11/2 0002 下午 2:08
 **/
@Configuration
public class DruidConfig {

    /**
     * master数据源
     * */
    @Bean("Master")
    @ConfigurationProperties("spring.datasource.oracle.master")
    public DataSource masterDataSource()
    {
        return new DruidDataSource();
    }

    /**
     * slave数据源
     * */
//    @Bean("Slave")
//    @ConfigurationProperties("spring.datasource.oracle.slave")
//    public DataSource slaveDataSource()
//    {
//        return new DruidDataSource();
//    }

    @Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource dataSource(@Qualifier("Master")DataSource masterDataSource) {

        Map<Object, Object> targetDataSources = new HashMap<>(2);
        targetDataSources.put("Master", masterDataSource);

        return new DynamicDataSource(masterDataSource, targetDataSources);

    }


    @Bean(name = "oracleJdbcTemplate")
    @Primary
    public JdbcTemplate oracleJdbcTemplate(@Qualifier("dynamicDataSource") DynamicDataSource dataSource) {
        return new JdbcTemplate(dataSource.getResolvedDefaultDataSource());
    }

//    @Bean
//    public SqlSessionFactory sqlSessionFactory(@Qualifier("dynamicDataSource") DynamicDataSource dataSource) throws Exception {
//
//        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
//        sessionFactory.setDataSource(dataSource);
//        MybatisConfiguration configuration = new MybatisConfiguration();
//        configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
//        configuration.setJdbcTypeForNull(JdbcType.NULL);
//        configuration.setMapUnderscoreToCamelCase(true);//开启下划线转驼峰
//        sessionFactory.setConfiguration(configuration);
//        return sessionFactory.getObject();
//    }

}